package com.c.authen.modules.sys.service.impl;

import com.c.authen.common.utils.Constant;
import com.c.authen.modules.sys.dao.SysMenuDao;
import com.c.authen.modules.sys.dao.SysUserDao;
import com.c.authen.modules.sys.entity.SysMenuEntity;
import com.c.authen.modules.sys.entity.SysUserEntity;
import com.c.authen.modules.sys.service.ShiroService;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authc.UnknownAccountException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service("shiroService")
@Transactional
public class ShiroServiceImpl implements ShiroService {
    @Autowired
    private SysMenuDao sysMenuDao;
    @Autowired
    private SysUserDao sysUserDao;

    @Override
    public Set<String> getUserPermissions(long userId) {
        List<String> permsList;

        //系统管理员，拥有最高权限
        if(userId == Constant.SUPER_ADMIN){
            List<SysMenuEntity> menuList = sysMenuDao.selectList(null);
            permsList = new ArrayList<String>(menuList.size());
            for(SysMenuEntity menu : menuList){
                permsList.add(menu.getPerms());
            }
        }else{
            permsList = sysUserDao.queryAllPerms(userId);
        }

        //用户权限列表
        Set<String> permsSet = new HashSet<String>();
        for(String perms : permsList){
            if(StringUtils.isBlank(perms)){
                continue;
            }
            permsSet.addAll(Arrays.asList(perms.trim().split(",")));
        }
        return permsSet;
    }

//    @Override
//    public SysUserTokenEntity queryByToken(String token) {
//        return sysUserTokenDao.queryByToken(token);
//    }

    @Override
    public SysUserEntity queryUser(Long userId) {
        //查询用户信息
        SysUserEntity user = new SysUserEntity();
        user.setUserId(userId);
        user = sysUserDao.selectOne(user);

        //账号不存在
        if(user == null) {
            throw new UnknownAccountException("账号或密码不正确");
        }
        return user;
    }
}
